<?php

namespace Yolo\Components\Validator;

use Hyperf\Contract\MessageBag;
use Yolo\Di\Annotations\Singleton;
use Yolo\Logs\Log;

/**
 * Class ValidatorFactory.
 * @method MessageBag|null validate(string|array $rules, array $data, array $messages = [], array $attributes = [])
 */
#[Singleton]
class ValidatorFactory
{
    /**
     * @var array 自定义验证规则
     */
    private array $rules = [];

    public function __construct(
        private readonly ValidatorInterface $validator,
        private readonly Log $log
    ){}

    public function __call($name, $arguments)
    {
        if (strtolower($name) === 'validate' && is_string($arguments[0]) && str_starts_with($arguments[0], '@')) {

            $rules = $this->rules[$arguments[0]] ?? null;
            if (!$rules) { // 没有找到验证规则，则不进行校验
                $this->log->warn([
                    'action' => 'validate_rules_not_found',
                    'message' => 'Invalid validation rules: ' . $arguments[0],
                    'data' => [],
                ]);
                return null;
            }

            $arguments[0] = $rules;
        }
        return $this->validator->$name(...$arguments);
    }

    /**
     * 注册自定义验证规则
     * @param string $name 验证规则名称
     * @param array $rules 验证规则
     * @return void
     */
    public function registryValidationRules(string $name, array $rules): void
    {
        $this->rules["@$name"] = $rules;
    }
}
